<?php
namespace App\Admin\Actions;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Database\Eloquent\Model;

/**
 * 后台通用修改功能
 */
trait Update
{

	public function update(Request $request, ActionSetter $setter, $id)
	{
		abort_unless(method_exists($this, 'modelName'), 500, class_basename($this).' 未设置 modelName() 方法');

		// 默认配置器与自定义配置器
		$this->updateSetter($setter);

		// 读取要修改的模型
		$model = $setter->call('find', $request, $id);
		abort_if($model===null, 500, "数据不存在#{$id}");
		abort_unless(($model instanceof Model), 500, 'find配置器返回的不是laravel模型');

		// 获得验证数据
		abort_unless($setter->has('validate'), 500, 'store必须设置validate配置器');
		$validated = $setter->call('validate', $request, $model);

		// 前置操作
		$setter->call('before', $model, $validated);

		// 修改操作
		$handle = $setter->call('handle', $model, $validated);

		// 后置操作
		$setter->call('after', $model, $validated, $handle);

		return [
			'code'    => 0,
			'message' => 'success',
			'data'    => $model,
		];
	}

	private function updateSetter($setter)
	{
		$setter->find(function($request, $id){
			return $this->modelName()::find($id);
		});
		$setter->handle(function($model, $validated){
			abort_unless($model->update($validated), 500, '系统错误, 修改失败');
			return true;
		});

		if( method_exists($this, 'actionUpdate') ){
			$this->actionUpdate($setter);
		}
		if( method_exists($this, 'storeAndUpdateValidate') ){
			$setter->validate([$this, 'storeAndUpdateValidate']);
		}
		abort_unless($setter->has('validate'), 500, 'store必须设置validate配置器');
	}
}

